package api

import (
	"github.com/gin-gonic/gin"
	"goadmin/localCache"
	"goadmin/logs"
	"goadmin/models"
	"goadmin/utils"
	"goadmin/wechatMiniprogram"
	"net/http"
)

type UserController struct {
	BaseController
}

func (con UserController) Index(c *gin.Context) {
	c.String(200, "我是一个api接口")
}

// 更新维信用户微信小程序的手机号
func (con UserController) UpdatePhone(c *gin.Context) {
	var req struct {
		EncryptedData string `json:"encryptedData" binding:"required" msg:"encryptedData必填"`
		Iv            string `json:"iv" binding:"required" msg:"iv必填"`
		PhoneCode     string `json:"phone_code" binding:"required" msg:"phone_code必填"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(),
			"code": 201,
		})
		return
	}
	userId, _ := c.Get("user_id")
	userInfo := models.User{}
	_ = models.DB.Where("id = ?", userId).Find(&userInfo).Error
	if userInfo.ID == 0 {
		con.errorMessage(c, "获取用户信息失败", 500)
	}
	//解密手机号
	phone, err := wechatMiniprogram.DecryptPhone(userInfo.Openid, req.Iv, req.EncryptedData)
	if err != nil {
		con.errorMessage(c, "手机号解析失败", 500)
		return
	}
	updateData := map[string]interface{}{
		"Mobile": phone,
	}
	result := models.DB.Model(&models.User{}).Where("id = ?", userInfo.ID).Updates(updateData)
	if result.Error != nil {
		// 数据库错误（如连接问题、约束冲突等）
		con.errorMessage(c, "程序错误", 201)
		return
	}
	userData := gin.H{
		"userInfo": userInfo,
	}
	con.successMessage(c, "登录成功", userData)
}

// 微信小程序登录
func (con UserController) WxLogin(c *gin.Context) {
	var req struct {
		Code string `json:"code" binding:"required" msg:"丢失code参数"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(), // 使用翻译后的错误消息
			"code": 201,
		})
		return
	}
	// 1. 拿 session：
	authSrv := wechatMiniprogram.WxClient.GetAuth() // 取出 auth 服务
	session, err := authSrv.Code2Session(req.Code)
	if err != nil {
		logs.Sugar().Info("code失败错误信息", err)
		con.errorMessage(c, "code无效,请更换", 500)
		return
	}
	if session.ErrCode != 0 {
		con.errorMessage(c, session.ErrMsg, 500)
		return
	}
	//存储缓存
	localCache.RedisDb.Set(localCache.RedisCoretxt, session.OpenID, session.SessionKey, 0).Err()
	userInfo := models.User{}
	_ = models.DB.Where("openid = ?", session.OpenID).Find(&userInfo).Error
	if userInfo.ID == 0 {
		insertData := map[string]interface{}{
			"Mobile": "",
			"Openid": session.OpenID,
			"RoleId": 0,
		}
		result := models.DB.Model(&models.User{}).Create(insertData)
		if result.Error != nil {
			con.errorMessage(c, "程序错误,插入失败", 201)
			return
		}
	}
	// 2. 以 openid 为 userId 生成 JWT
	accessToken, err := utils.GenerateToken(userInfo.ID, userInfo.Openid)
	if err != nil {
		con.errorMessage(c, "获取token失败", 500)
		return
	}
	userData := gin.H{
		"accessToken": accessToken,
		"userInfo":    userInfo,
	}
	con.successMessage(c, "登录成功", userData)
}

// 获取用户信息
func (con UserController) UserDetail(c *gin.Context) {
	userId, _ := c.Get("user_id")
	userInfo := models.User{}
	_ = models.DB.Where("id = ?", userId).Find(&userInfo).Error
	if userInfo.ID == 0 {
		con.errorMessage(c, "获取用户信息失败", 500)
	} else {
		con.successMessage(c, "登录成功", userInfo)
	}
}

func (con UserController) SendMessage(c *gin.Context) {
	utils.SendAdminNoticeMsg("李某", "17326062026", "2025-06-10")
}
